<template>
 <div id="dsText" :class="{ellipsis: hasEllipsis}" :style="{color: color, fontSize: fontSize + 'rem'}">
   {{text}}
   <span style="display: none;">{{strlen}}</span>
 </div>
</template>

<script>
/**
 * @author 'yejinbo'
 * @description `基础组件-文本`
 */
export default {
  data () {
    return {
      hasEllipsis: false,
      rem2px: 16,
      charRate: 2,
      lines: 2,
      lastCtrl: 3,
      fontSize: 1.2,
      cnExp: /[[\u4e00-\u9fa5]|\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5]]/
    }
  },
  props: {
    text: {
      type: String
    },
    color: {
      type: String
    }
  },
  methods: {
    cut (hasEllipsis) {
      this.hasEllipsis = hasEllipsis
    }
  },
  mounted () {
    this.rem2px = parseInt(window.getComputedStyle(document.documentElement)['fontSize']) || 16
  },
  computed: {
    strlen () {
      let len = this.text.length
      let l = 0
      this.$nextTick(() => {
        let _wd = this.$el.clientWidth / Math.ceil(this.fontSize * this.rem2px) * this.charRate * this.lines - this.lastCtrl
        for (let i = 0; i < len; i++) {
          let flag = this.cnExp.test(this.text[i])
          flag ? l += 2 : l++
        }
        if (l > _wd) this.cut(true)
        else this.cut()
      })
      return ''
    }
  }
}
</script>

<style scoped lang="stylus">
  #dsText
    display: inline-block
    padding: 1% 2.2%
    width: 100%
    line-height: 1.85
    height: 4.4rem
    word-break: break-all
    overflow: hidden
    color: #bd1919
    font-size: 1.2rem
    box-sizing: border-box
    position: relative
  .ellipsis:after
    content: "..."
    font-weight: bold
    position: absolute
    bottom: -5px
    right: -4px
    padding-right: 4px
    background: url('../../img/elips.png') repeat
</style>
